<script>
import { GetBiscuitInfo, updateInfo } from "@/services/biscuit";
import { GetCartCount } from "@/services/cart";
import { userLogin } from "@/services/utils";

import { message, generateSign, randomString, ossImg, ObjectToQueryString } from "@/utils/utils";
import sr from "sr-sdk-wxapp";

require("./static/js/Analytics/cct-wxa");
export default {
  globalData: {
    user: uni.getStorageSync("USER_INFO") || {},
    statusBarHeight: 0,
    tabBarHeight: 0,
    cartCount: 0,
  },
  onLaunch: function () {
    // console.log("App Launch");
	//加载字体
		uni.loadFontFace({
			global: true, // 全局生效
			family: 'fzround', // 自定义字体名称
	    source: 'url("'+ossImg("others/2025Autumn/FZCYZT.TTF")+'")', // 字体的HTTPS链接
			success: () => {
				console.log('字体加载成功');
			},
			fail: (err) => {
				console.error('字体加载失败', err);
			}
		});

    const updateManager = uni.getUpdateManager();

    // 检查小程序是否有新版本发布
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
    });

    // 小程序有新版本，则静默下载新版本，做好更新准备
    updateManager.onUpdateReady(function (res) {
      uni.showModal({
        title: "更新提示",
        content: "新版本已经准备好，点击确定重新启动",
        showCancel: false,
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate();
          }
        },
      });
    });

    updateManager.onUpdateFailed(function (res) {
      // 新的版本下载失败
      uni.showModal({
        title: "已经有新版本了哟~",
        content: "新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~",
      });
    });

    const skipLoadingPaths = ['packageWanXin/pages/index/index', 'campaign/pages/TheArtofRePlay/index', 'pages/jump/jump']
    const skipLoadingPaths2 = ['pages/jump/jump']

    if (
      [
        "campaign/pages/panda2023/scanCode",
        "campaign/pages/panda2023/index",
        "campaign/pages/panda2023/webview",
      ].includes(uni.getLaunchOptionsSync().path)
    ) {
      uni.redirectTo({ url: "campaign/pages/panda2023/pandaLoading" });
    } else if (
      ["campaign/pages/minioreo/index"].includes(
        uni.getLaunchOptionsSync().path
      )
    ) {
      uni.redirectTo({ url: "campaign/pages/minioreo/pandaLoading" });
    } else if (
      [
        "packageTokaeGame/index/index",
        "packageTokaeGame/form/form",
        "packageTokaeGame/formv2/form",
      ].includes(uni.getLaunchOptionsSync().path)
    ) {
      uni.redirectTo({ url: "/packageTokaeGame/loading/loading" });
    } else if (
      [
        "campaign/pages/ultraman/webview",
        "campaign/pages/ultraman/index",
      ].includes(uni.getLaunchOptionsSync().path)
    ) {
      uni.redirectTo({ url: "campaign/pages/ultraman/loading" });
    }
    else if (
        ["pages/2023oreocore/index", "campaign/pages/oreoQ4/webview"].includes(
            uni.getLaunchOptionsSync().path
        )
    ) {
      uni.redirectTo({ url: "campaign/pages/oreoQ4/loading" });
    }
    // DIY小狗表情包跳转处理
    else if (['campaign/pages/maltese/index'].includes(uni.getLaunchOptionsSync().path)) {
      uni.redirectTo({ url: "campaign/pages/maltese/index" + `?${ObjectToQueryString(uni.getLaunchOptionsSync().query)}` })
    }
    else if (skipLoadingPaths2.includes(uni.getLaunchOptionsSync().path)) {
      return
    }
    // 需要跳过通用loading的页面
    else if (skipLoadingPaths.includes(uni.getLaunchOptionsSync().path)) {
      const path = skipLoadingPaths.find(path => path === uni.getLaunchOptionsSync().path)
      uni.redirectTo({ url: path + `?${ObjectToQueryString(uni.getLaunchOptionsSync().query)}` })
    }
    // 蛋仔loading
    else if (['campaign/pages/AiryCakeIntroduction/index', 'campaign/pages/cloudsample/index'].includes(uni.getLaunchOptionsSync().path)) {
      const path = 'campaign/pages/cloudsample/loading'
      uni.redirectTo({ url: path + `?${ObjectToQueryString(uni.getLaunchOptionsSync().query)}` })
    }
    // 蛋仔loading2025
    else if (['campaign/pages/2025OreoSnacksXEggyParty/index'].includes(uni.getLaunchOptionsSync().path)) {
      const path = 'campaign/pages/2025OreoSnacksXEggyParty/loading'
      uni.redirectTo({ url: path + `?${ObjectToQueryString(uni.getLaunchOptionsSync().query)}` })
    }
    // 熊猫3.0loading
    else if (['campaign/pages/panda2024/index'].includes(uni.getLaunchOptionsSync().path)) {
      const path = 'campaign/pages/panda2024/loading'
      uni.redirectTo({ url: path + `?${ObjectToQueryString(uni.getLaunchOptionsSync().query)}` })
    }
    else {
      uni.redirectTo({ url: "/pages/loading/loading" });
    }
  },
  onShow: function () {
    if (uni.getLaunchOptionsSync().query.scene) {
      uni.setStorageSync("SCENE", uni.getLaunchOptionsSync().query.scene);
    }
    uni.getSystemInfo({
      success: (result) => {
        const { screenHeight, windowHeight, statusBarHeight } = result;
        this.globalData.statusBarHeight = result.statusBarHeight + 44;
        this.globalData.tabBarHeight =
          screenHeight - windowHeight - statusBarHeight;
      },
    });

    if (!uni.getStorageSync("OPENID")) {
      this.getUserLoginInfo();
    }
  },
  onHide: function () {
    // console.log("App Hide");
  },
  methods: {
    emdlz2() {
      const currentPage = getCurrentPages().at(-1)
      const trackInfo = Array.from(arguments)
      // 店铺装修事件只在首页触发
      if (trackInfo.includes('standardized_components') && currentPage.route !== 'pages/home/home') return
      getApp().emdlz(...arguments)
    },
    // 绑定全局用户数据
    getUserInfo() {
      return new Promise(async (resolve, reject) => {
        const res = await GetBiscuitInfo();
        if (res?.code === 200) {
          this.globalData.user = res.data;
          uni.setStorageSync("USER_INFO", JSON.stringify(res.data));
          if (uni.getStorageSync("OPENID")) {
            getApp().emdlz2(
              "set",
              "user",
              "openid",
              uni.getStorageSync("OPENID")
            );
          }
          if (uni.getStorageSync("UNIONID")) {
            getApp().emdlz2(
              "set",
              "user",
              "unionId",
              uni.getStorageSync("UNIONID")
            );
          }

          if (this.globalData.user.memberScore.memberId) {
            getApp().emdlz2(
              "set",
              "user",
              "memberid",
              this.globalData.user.memberScore.memberId
            );
          }
          resolve(res.data);
        } else {
          reject(res.message);
        }
      });
    },

    // 全局授权
    getWechatUserProfile(toPath) {
      const loginParam = {
        type: 1,
      };
      // 静默拿取微信用户的 openId 与 unionId 信息
      uni.login({
        provider: "weixin",
        success: async (res) => {
          loginParam.code = res.code;
          loginParam.inviterId = uni.getStorageSync("inviterId");
          const { data } = await userLogin(loginParam);
          uni.setStorageSync("TOKEN", data?.accessToken);

          this.getUserInfo()
            .then(async () => {
              if (
                this.globalData.user.nickname !== null ||
                this.globalData.user.nickname !== ""
              ) {
                if (
                  this.globalData.user.phone === null ||
                  this.globalData.user.phone === ""
                ) {
                  uni.setStorageSync("REDIRECT_URI", JSON.stringify(toPath));
                  uni.navigateTo({ url: "/pages/vip/register" });
                  return;
                }
                if (!toPath) return;
                if (toPath.redirect)
                  return uni.redirectTo({ url: toPath.path });
                if (toPath.navigate)
                  return uni.navigateTo({ url: toPath.path });
                if (toPath.navigateBack) return uni.navigateBack({ delta: 1 });
                uni.switchTab({
                  url: toPath.path,
                  success: function (e) {
                    var page = getCurrentPages().pop();
                    if (page == undefined || page == null) return;
                    page.onShow();
                  },
                });
              }
            })
            .catch((err) => {
              message(err);
            });

          sr.track("login_wxapp", {
            // more...
          });
        },
      });

      if (
        this.globalData.user.nickname === null ||
        this.globalData.user.nickname === ""
      ) {
        uni.getUserProfile({
          desc: "用于完善会员资料",
          lang: "zh_CN",
          success: async (res) => {
            if (res.errMsg === "getUserProfile:ok") {
              loginParam.inviterId = uni.getStorageSync("inviterId");
              const up = await updateInfo({
                nickname: res.userInfo.nickName,
                icon: res.userInfo.avatarUrl,
              });

              this.getUserInfo()
                .then(async () => {
                  getApp().emdlz2("set", "user", "openid", data.openId);
                  getApp().emdlz2("set", "user", "unionId", data.unionId);
                  if (this.globalData.user.memberScore.memberId) {
                    getApp().emdlz2(
                      "set",
                      "user",
                      "memberid",
                      this.globalData.user.memberScore.memberId
                    );
                  }

                  if (
                    this.globalData.user.phone === null ||
                    this.globalData.user.phone === ""
                  ) {
                    uni.setStorageSync("REDIRECT_URI", JSON.stringify(toPath));
                    uni.navigateTo({ url: "/pages/vip/register" });
                    return;
                  }
                  if (!toPath) return;
                  if (toPath.redirect)
                    return uni.redirectTo({ url: toPath.path });
                  if (toPath.navigate)
                    return uni.navigateTo({ url: toPath.path });
                  if (toPath.navigateBack)
                    return uni.navigateBack({ delta: 1 });
                  uni.switchTab({
                    url: toPath.path,
                    success: function (e) {
                      var page = getCurrentPages().pop();
                      if (page == undefined || page == null) return;
                      page.onShow();
                    },
                  });
                })
                .catch((err) => {
                  message(err);
                });
            }
          },
          fail: (err) => {
            uni.showToast({
              title: "你取消了授权",
              icon: "none",
            });
          },
        });
      }
    },

    // 获取购物车数量
    getCartCount() {
      return new Promise(async (resolve) => {
        const res = await GetCartCount();
        if (res?.code === 200) {
          this.globalData.cartCount = res.data;
          resolve(res.data);
        }
      });
    },

    // 全局记录
    accessLogAdd() {
      return new Promise(async (resolve) => {
        // 获取当前页面的实例
        let pages = getCurrentPages();
        // 获取的才是当前页面实例
        let currentPage = pages[pages.length - 1];
        const body = {
          path: currentPage.$page.fullPath.split("?")[0],
          query: currentPage.$page.fullPath.split("?")[1] || "",
          wxScene: uni.getLaunchOptionsSync().scene,
          scene: uni.getLaunchOptionsSync().query.scene
            ? uni.getLaunchOptionsSync().query.scene
            : uni.getStorageSync("SCENE") || "",
          channelId: "",
          type: "default",
          nonce: randomString(),
          timestamp: parseInt(new Date().getTime() / 1000),
        };
        // console.log("sence----------------------", body);

        uni.request({
          url: `${process.env.BASE_API}s-mall/api/access-log/loginaccess`,
          method: "post",
          data: {
            ...body,
            ...{ sign: generateSign(body) },
          },
          header: {
            Authorization: uni.getStorageSync("TOKEN")
              ? `Bearer ${uni.getStorageSync("TOKEN")}`
              : "",
          },
        });

        // await accessLogAdd({ ...body, ...{ sign: generateSign(body) } });
        resolve("");
      });
    },

    // 全局登录接口，回调返回登录接口返回信息
    getUserLoginInfo() {
      return new Promise(async (resolve, reject) => {
        uni.login({
          provider: "weixin",
          success: async (res) => {
            const loginParam = {
              type: 1,
            };
            loginParam.code = res.code;
            loginParam.nickName = "微信用户";
            loginParam.avatar = ossImg("personal/moren_avatar.png");

            if (uni.getStorageSync("inviterId")) {
              loginParam.inviterId = uni.getStorageSync("inviterId");
            }

            const loginRes = await userLogin(loginParam);
            if (loginRes.code === 200) {
              resolve(loginRes.data);
              uni.setStorageSync("OPENID", loginRes.data?.openId);
              uni.setStorageSync("UNIONID", loginRes.data?.unionId);
              uni.setStorageSync("TOKEN", loginRes.data?.accessToken);
              getApp().emdlz2("set", "user", "openid", loginRes.data.openId);
              getApp().emdlz2("set", "user", "unionId", loginRes.data.unionId);
              sr.track("login_wxapp", {
                // more...
              });
            } else {
              reject(loginRes);
            }
          },
        });
      });
    },

    // 有数调用
    sr() {
      return sr;
    },
  },
};
</script>

<style lang="less">
/*每个页面公共css */

@import "./wxcomponents/vant/common/index.wxss";
@import "@/static/css/theme.less";
page {
  background-color: #eeeeee;
  color: #0d0d0d;
}

.line-clamp-2 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.price {
  position: relative;
  line-height: 1;
  display: flex;
  align-items: flex-end;

  .master {
    font-size: 16px;
    font-weight: bold;
  }

  label {
    font-size: 12px;
  }

  &::before {
    content: "¥";
    font-size: 12px;
  }
}

.order-tag {
  width: 58px;
  height: 22px;
  line-height: 22px;
  background: #e8f0fb;
  color: #0058c6;
  font-size: 12px;
  text-align: center;
  font-weight: 500;
}

.cover {
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  background-image: url("@{ossPath}others/moren_icon@2x.png");
}

.oreo-service {
  width: 55px;
  height: 30px;
  background: #0058c6;
  border-radius: 10px 0 0 10px;
  position: fixed;
  color: white;
  font-size: 12px;
  padding-left: 6px;
  right: 0;
  bottom: 118px;
  z-index: 999;
  display: flex;
  align-items: center;
  box-sizing: border-box;

  image {
    width: 16px;
    height: 16px;
    margin-right: 5px;
  }
}
</style>
